package com.hj.auth.common.filter;


import com.hj.auth.common.pojo.LoginUser;
import com.hj.auth.common.util.JwtTokenUtil;
import com.hj.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 校验用户token是否过期
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        //获取用户信息
        LoginUser loginUser = jwtTokenUtil.getLoginUser(request);
        //authentication为空  说明用户未登陆
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //如果用户信息为空 说明token失效  需要查询登陆  默认过期时间30分钟
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(authentication)) {
            jwtTokenUtil.verifyToken(loginUser);//刷新用户过期时间
            //把token设置到security中
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //把token设置为上下文对象
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request,response);
    }
}
